<?php

class EditAction extends CAction {

	public $modelName = '';
	protected $_successUrl = '';
	public $updateSuccess = '操作成功';
	public $updateFailed = '操作失败';
	public $createSuccess = '操作成功';
	public $createFailed = '操作失败';
	
	public $beforeRender = '';
	
	public $ajaxName = 'ajax';
	public $ajaxId = '';
	
	public $view;
	
	public function getSuccessUrl() {
		return $this->_successUrl
			? $this->_successUrl 
			: $this->_successUrl = $this->controller->createUrl(
				$this->id
			);
	}
	
	public function setSuccessUrl($url) {
		$this->_successUrl = $url;
	}
	
	public function run($id = null) {
		$c = $this->controller;
		$v = $c->createView($this->view);
		
		$modelName = $this->modelName;
		$model = $c->loadModel($id);
		
		$this->performAjaxValidation($model);
		
		if($this->loadData($model)) {
			
			if($model->save()) {
				Yii::app()->user->setFlash(FLASH::OP_RESULT_SUCCESS, $id 
					? $this->updateSuccess
					: $this->createSuccess
				);
				$this->goSuccess();
			} else {
				Yii::app()->user->setFlash(FLASH::OP_RESULT_FAILED, $id
					? $this->updateFailed
					: $this->createFailed
				);
			}
		}
		if(($foo=$this->beforeRender) != null) $foo($c, $model);
		$v->addViewData('model', $model);
		$v->render();
	}
	
	public function loadData($model) {
		if(isset($_POST[$this->modelName])) {
			$model->attributes = $_POST[$this->modelName];
			return true;
		} else {
			return false;
		}
	}
	
	public function render($view, $fileName) {
		$view->render($fileName);
	}
	
	public function goSuccess() {
		$this->controller->redirect($this->getSuccessUrl());
	}
	
	protected function performAjaxValidation($model)
	{
	    if(isset($_POST[$this->ajaxName]) && $_POST[$this->ajaxName]===$this->ajaxId)
	    {
	        echo CActiveFormAdv::validate($model);
	        Yii::app()->end();
	    }
	}
	
	
}

?>